// 函数组件
import React, { useState, useEffect } from 'react';
import './css/OrderReason.css'

import { Card, Table, Space, Button, Switch, Modal, message } from 'antd'
const { Column, ColumnGroup } = Table;
import { ExclamationCircleFilled } from '@ant-design/icons';
const { confirm } = Modal;
import EditModal from './orderReason/EditModal';
import AddModal from './orderReason/AddModal';
import { getAllReason, delReason, updateReasonState } from '../../../api/OrderApi'
import type { TableRowSelection } from 'antd/es/table/interface';
import myContext from '../../../utils/myContext'



interface DataType {
    key: React.Key;
    appliId: number;
    reasonDescription: string;
    // sort:number;
    startUse: boolean;
    insertTime: string
}

function OrderReason() {

    const [data, setData] = useState<DataType[]>()  //所有数据
    const [isEditModalOpen, setIsEditModalOpen] = useState<boolean>(false); //编辑弹框显示隐藏
    const [isAddModalOpen, setIsAddModalOpen] = useState<boolean>(false); //添加弹框显示隐藏
    const [clickRow, setClickRow] = useState<DataType | null>(null);//点击编辑的那一行信息
    const [pageCount, setPageCount] = useState<number>()  //退换原因条数
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);  //多选框
    const [pageSize, setPageSize] = useState<number>(2) //每页条数
    const [currentPage, setCurrentPage] = useState<number>(1) //当前第几页
    // 多选框
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('newSelectedRowKeys', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    // 表格多选配置
    const rowSelection: TableRowSelection<DataType> = {
        selectedRowKeys,
        onChange: onSelectChange,
        selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,
            {
                key: 'odd',
                text: 'Select Odd Row',
                onSelect: (changableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return false;
                        }
                        return true;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
            {
                key: 'even',
                text: 'Select Even Row',
                onSelect: (changableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return true;
                        }
                        return false;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
        ],
    };
    // 初始化数据
    useEffect(() => {
        getAll()
    }, [])


    // 获取所有数据
    const getAll = () => {
        getAllReason({
            pageNum: currentPage,
            size: pageSize
        }).then(res => {
            setData(res.data.aftereasonList);
            setPageCount(res.data.count)
        }).catch(err => {
            console.log('err777', err);
            message.error('服务器出错啦~~~')
        })
    }

    // 编辑状态是否开启
    const changeSwitch = (id: number, isOpen: boolean) => {
        console.log('checked', id);
        console.log('isOpen', !isOpen);
        let obj = {
            orderId: id,
            startUse: isOpen == true ? 0 : 1
        }
        // 发起请求
        updateReasonState([obj]).then(res => {
            message.info('请点击编辑按钮进行修改状态')
        }).catch(err => {
            console.log('err', err);
            message.error('服务器错误')
        })

    };


    // 删除某一条数据
    const delHandle = (record: any) => {
        confirm({
            title: '提示:',
            icon: <ExclamationCircleFilled />,
            content: '您确定要删除这一行吗？删除后无法恢复！',
            cancelText: '取消',
            okText: '确认',
            onOk() {
                // 点击确定发起请求
                delReason(
                    [record.appliId]
                ).then(res => {
                    getAll()
                    // if (res.data.code == 200) {
                    message.success('删除成功！')
                    // } else {
                    //     message.info('删除失误啦！')
                    // }
                }).catch(err => {
                    console.log('err', err);
                    message.error('服务器出错啦~~~')
                })
            },
        });
    };


    // 批量删除
    const deltotalHandle = () => {
        confirm({
            title: '提示:',
            icon: <ExclamationCircleFilled />,
            content: '您确定要批量删除这些数据吗？删除后无法恢复！',
            cancelText: '取消',
            okText: '确认',
            onOk() {

                console.log('selectedRowKeys', selectedRowKeys);
                if (selectedRowKeys.length <= 0) {
                        message.info('请先选择再进行操作')
                } else {
                    // 点击确定发起请求
                    delReason(
                        selectedRowKeys
                    ).then(res => {
                        getAll()
                        // if (res.data.code == 200) {
                        message.success('删除成功！')
                        // } else {
                        //     message.info('删除失误啦！')
                        // }
                    }).catch(err => {
                        console.log('err', err);
                        message.error('服务器错误啦')
                    })
                }


            },
        });
    }

    // 编辑对应行的所有信息
    const editHandle = (record: any) => {
        setIsEditModalOpen(true)
        setClickRow(record)
    }


    // 批量编辑状态
    const editotalHandle = (startUse: number) => {
        let arr = selectedRowKeys.map((item: any) => {
            return {
                orderId: item,
                startUse: startUse
            }
        })
        console.log('arr', arr);
        console.log('arr', arr.length);
        if (arr.length <= 0) {
            console.log('xuanz');

            message.info(`请先选择再进行操作`)
        } else {
            // 发起请求
            console.log(12);

            updateReasonState(arr).then(res => {
                let str = startUse == 1 ? '启用' : '关闭'
                message.success(`批量${str}成功`)
                getAll()
            }).catch(err => {
                console.log('err', err);
                message.error('服务器错误')
            })
        }

    }

    // 关闭编辑框
    const closeEdit = () => {
        setIsEditModalOpen(false)
    }
    // 关闭添加框
    const closeAdd = () => {
        setIsAddModalOpen(false)
    }

    // 添加
    const addHandle = () => {
        setIsAddModalOpen(true)
    }

    // 页码改变的函数
    const pageChange = (page: number, pageSize: number) => {
        setPageSize(pageSize)
        setCurrentPage(page)
        getAllReason({
            pageNum: page,
            size: pageSize,
        }).then(res => {
            setData(res.data.aftereasonList)
            setPageCount(res.data.count)
            // 设置当前页和每页条数
            setPageSize(pageSize)
            setCurrentPage(page)
        }).catch(err => {
            console.log('页码改变出错', err);
            message.error('服务器出错啦')
        })
    }

    return (
        <div className='OrderReason'>
            <myContext.Provider value={{ getAll }}>
                <p className='head'>退换货原因设置</p>
                <Card title="数据列表" type="inner" className='orderreason_content'>
                    <Button className='add' onClick={addHandle}>添加</Button>
                    <Button className='deltotal' id='del' onClick={deltotalHandle}>批量删除</Button>
                    <Button className='edittotal1 edmit' onClick={() => editotalHandle(1)}>启用</Button>
                    <Button className='edittotal2 edmit' onClick={() => editotalHandle(0)}>关闭</Button>
                    <Table bordered={true} dataSource={data} rowKey={(item) => item.appliId}
                        rowSelection={rowSelection}
                        pagination={{
                            position: ['bottomCenter'],
                            total: pageCount,
                            defaultPageSize: pageSize,
                            defaultCurrent: currentPage,
                            pageSizeOptions: [2, 3, 5],
                            showSizeChanger: true,
                            showQuickJumper: true,
                            onChange: pageChange,
                            showTotal: (pageCount: number) => `共有 ${pageCount} 条数据`
                        }}
                    >
                        <Column title="原因描述" dataIndex="reasonDescription" key="reasonDescription" />
                        <Column title="排序" dataIndex="appliId" key="appliId" />
                        <Column title="是否启用" dataIndex="startUse" key="startUse"
                            render={(_: any, record: DataType) => (
                                // <span>{state[0].goods_price}</span>
                                <Space>
                                    <Switch checked={record.startUse} onChange={() => changeSwitch(record.appliId, record.startUse)}></Switch>
                                </Space>
                            )}
                        />
                        <Column title="添加时间" dataIndex="insertTime" key="insertTime" />
                        <Column title="操作" dataIndex="operation" key="operation"
                            render={(_: any, record: DataType) => (
                                // <span>{state[0].goods_price}</span>
                                <Space>
                                    <Button className='edmit' onClick={() => editHandle(record)}>编辑</Button>
                                    <Button id='del' onClick={() => delHandle(record)}>删除</Button>
                                </Space>
                            )}
                        />
                    </Table>
                </Card>

                {/* 编辑弹框 clickRow={clickRow}*/}
                <EditModal isEditModalOpen={isEditModalOpen} close={closeEdit} clickRow={clickRow} ></EditModal>

                {/* 添加弹框 */}
                <AddModal isModalOpen={isAddModalOpen} close={closeAdd}></AddModal>
            </myContext.Provider>

        </div>
    )
}

export default OrderReason